import 'package:get/get.dart';
import 'package:raze/lore/glyph/user_essence.dart';

/// 用户状态管理
/// 全局用户状态，提供登录、注册、查询等功能
class UserChronicle extends GetxController {
  // 所有用户列表
  final _userList = <UserEssence>[].obs;

  // 当前登录用户
  final _currentUser = Rxn<UserEssence>();

  /// 获取所有用户列表
  List<UserEssence> get userList => _userList;

  /// 获取当前登录用户
  UserEssence? get currentUser => _currentUser.value;

  /// 是否已登录
  bool get isLoggedIn => _currentUser.value != null;

  @override
  void onInit() {
    super.onInit();
    _initializeDefaultUsers();
  }

  /// 初始化默认用户数据
  void _initializeDefaultUsers() {
    _userList.value = [
      UserEssence(
        id: '1',
        account: 'admin',
        password: '123456',
        username: 'Chloe',
        signature: 'Fresh green after rain',
        avatar: 'assets/images/avatar1.png',
      ),
      UserEssence(
        id: '2',
        account: 'user002',
        password: '123456',
        username: 'Grace',
        signature: 'Life blooms after rain',
        avatar: 'assets/images/avatar2.png',
      ),
      UserEssence(
        id: '3',
        account: 'user003',
        password: '123456',
        username: 'Piper',
        signature: 'Every raindrop nurtures life',
        avatar: 'assets/images/avatar3.png',
      ),
      UserEssence(
        id: '4',
        account: 'user004',
        password: '123456',
        username: 'Daisy',
        signature: 'Exploring post-rain gardens',
        avatar: 'assets/images/avatar4.png',
      ),
      UserEssence(
        id: '5',
        account: 'user005',
        password: '123456',
        username: 'Ethan',
        signature: "Capturing nature's beauty",
        avatar: 'assets/images/avatar5.png',
      ),
      UserEssence(
        id: '6',
        account: 'user006',
        password: '123456',
        username: 'Mason',
        signature: 'Growing quietly with rain',
        avatar: 'assets/images/avatar6.png',
      ),
      UserEssence(
        id: '7',
        account: 'user007',
        password: '123456',
        username: 'Daniel',
        signature: 'Sharing plant moments',
        avatar: 'assets/images/avatar7.png',
      ),
      UserEssence(
        id: '8',
        account: 'user008',
        password: '123456',
        username: 'Joseph',
        signature: 'Rain brings healing greens',
        avatar: 'assets/images/avatar8.png',
      ),
      UserEssence(
        id: '9',
        account: 'user009',
        password: '123456',
        username: 'Caleb',
        signature: 'Love every green after rain',
        avatar: 'assets/images/avatar9.png',
      ),
      UserEssence(
        id: '10',
        account: 'user010',
        password: '123456',
        username: 'Willow',
        signature: "Nature's gift after rain",
        avatar: 'assets/images/avatar10.png',
      ),
    ];
  }

  /// 用户登录
  /// [account] 账号
  /// [password] 密码
  /// 返回登录结果，成功返回true，失败返回false
  bool performLogin(String account, String password) {
    final user = _userList.firstWhereOrNull(
      (user) => user.account == account && user.password == password,
    );

    if (user != null) {
      _currentUser.value = user;
      return true;
    }
    return false;
  }

  /// 用户注册
  /// [account] 账号
  /// [password] 密码
  /// [username] 用户名
  /// [signature] 签名
  /// [avatar] 头像路径
  /// 返回注册结果，成功返回true，失败返回false（账号已存在）
  bool performRegister(
    String account,
    String password,
    String username,
    String signature,
    String avatar,
  ) {
    // 检查账号是否已存在
    final existingUser = _userList.firstWhereOrNull(
      (user) => user.account == account,
    );

    if (existingUser != null) {
      return false; // 账号已存在
    }

    // 创建新用户
    final newUser = UserEssence(
      id: (_userList.length + 1).toString(),
      account: account,
      password: password,
      username: username,
      signature: signature,
      avatar: avatar,
    );

    _userList.add(newUser);
    return true;
  }

  /// 退出登录
  void performLogout() {
    _currentUser.value = null;
  }

  /// 根据ID查询用户信息
  /// [userId] 用户ID
  /// 返回用户信息，不存在返回null
  UserEssence? queryUserById(String userId) {
    return _userList.firstWhereOrNull((user) => user.id == userId);
  }

  /// 根据账号查询用户信息
  /// [account] 账号
  /// 返回用户信息，不存在返回null
  UserEssence? queryUserByAccount(String account) {
    return _userList.firstWhereOrNull((user) => user.account == account);
  }

  /// 更新当前用户信息
  /// [updatedUser] 更新后的用户信息
  void updateCurrentUser(UserEssence updatedUser) {
    final index = _userList.indexWhere((user) => user.id == updatedUser.id);
    if (index != -1) {
      _userList[index] = updatedUser;
      if (_currentUser.value?.id == updatedUser.id) {
        _currentUser.value = updatedUser;
      }
    }
  }

  /// 直接设置当前用户（用于 Apple 登录等不需要密码验证的场景）
  /// [user] 要设置为当前用户的用户对象
  void setCurrentUser(UserEssence user) {
    // 确保用户在列表中
    final foundUser = _userList.firstWhereOrNull(
      (u) => u.id == user.id || u.account == user.account,
    );
    if (foundUser != null) {
      _currentUser.value = foundUser;
    } else {
      // 如果用户不在列表中，直接设置为当前用户（可能是刚注册的用户）
      _currentUser.value = user;
    }
  }
}
